package codetop.microsoft.S51;

/**
 * @Author: 18362
 * @Create: 2022-09-01 17:19:21 星期四
 */
class Solution {

    private int res = 0;

    public int reversePairs(int[] nums) {
        mergeSort(nums, new int[nums.length], 0, nums.length-1);
        return res;
    }

    private void mergeSort(int[] nums, int[] temp, int left, int right) {
        if (left >= right)
            return;
        int mid = left + (right - left) / 2;
        mergeSort(nums, temp, left, mid);
        mergeSort(nums, temp, mid+1, right);
        merge(nums, temp, left, mid, right);
    }

    private void merge(int[] nums, int[] temp, int left, int mid, int right) {
        int i = left, j = mid+1, k = left;
        while (i <= mid && j <= right) {
            if (nums[i] <= nums[j]) {
                temp[k++] = nums[i++];
            } else {
                temp[k++] = nums[j];
                res += (mid + 1 - i);
                j++;
            }
        }
        while (i <= mid)
            temp[k++] = nums[i++];
        while (j <= right)
            temp[k++] = nums[j++];
        for (k = left; k<=right; ++k)
            nums[k] = temp[k];
    }
}